package pers.gxm.proxy;

import java.lang.reflect.InvocationTargetException;

public class PrinterProxy implements Printable{
    private String name;
    private Printable real;
    private String simpleClassName;
    public PrinterProxy(){}
    public PrinterProxy(String name){
        this.name = name;
    }

    public PrinterProxy(String name , String simpleClassName){
        this(name);
        this.simpleClassName = simpleClassName;
    }
    @Override
    public synchronized void setPrinterName(String name) {
        if(real != null){
            real.setPrinterName(name);
        }
        this.name = name;
    }

    @Override
    public String getPrinterName() {
        return this.name;
    }

    @Override
    public void print(String string) {
        try {
            realizeWithName();
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
//        realize();
        real.print(string);
    }

    private synchronized void realize(){
        if(real == null){
            real = new Printer(name);
        }
    }

    private synchronized void realizeWithName() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        if(real == null){
            real = (Printable) Class.forName(simpleClassName).getConstructor(String.class).newInstance(name);
        }
    }
}
